package com.ljfiction.book.MyView;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.v7.widget.CardView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.ljfiction.book.R;
import com.ljfiction.book.activitys.AnnouncementActivity;
import com.ljfiction.book.activitys.AuthorWealActivity;
import com.ljfiction.book.activitys.CreatBookActivity;
import com.ljfiction.book.activitys.LeaveActivity;
import com.ljfiction.book.activitys.MainActivity;
import com.ljfiction.book.activitys.MyAuthorMessageActivity;
import com.ljfiction.book.activitys.MyincomeActivity;
import com.ljfiction.book.activitys.PepperharvestActivity;
import com.ljfiction.book.activitys.ReaderAidActivity;
import com.ljfiction.book.tools.SettingManager;

/**
 * Created by Administrator on 2017/7/7.
 */

public class HomwriterWindow extends PopupWindow implements View.OnClickListener {
    private String TAG = HomwriterWindow.class.getSimpleName();
    private MainActivity mContext;
    private int mWidth;
    private int mHeight;
    private int statusBarHeight;
    private Bitmap mBitmap = null;
    private Bitmap overlay = null;
    private Diss disslistener;
    private Handler mHandler = new Handler();
    private Intent intent;
    private ImageView close;//关闭
    private CardView dian_earnx, dian_pepper, dian_message, dian_webtId, dian_fl;//收入，收获，消息
    private long sp = 0, su = 0, cc = 0, sp2 = 0, webtId = 0, fl = 0;
    private Canvas canvas;


    public HomwriterWindow(MainActivity context) {
        mContext = context;
    }

    public void init() {
        Rect frame = new Rect();
        mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        statusBarHeight = frame.top;
        DisplayMetrics metrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay()
                .getMetrics(metrics);
        mWidth = metrics.widthPixels;
        mHeight = metrics.heightPixels;

        setWidth(mWidth);
        setHeight(mHeight);
    }

    private Bitmap blur() {
        if (null != overlay) {
            return overlay;
        }
        long startMs = System.currentTimeMillis();
        View view = mContext.getWindow().getDecorView();
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        mBitmap = view.getDrawingCache();

        float scaleFactor = 8;//图片缩放比例；
        float radius = 10;//模糊程度
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor), Bitmap.Config.ARGB_8888);
        canvas = new Canvas(overlay);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(mBitmap, 0, 0, paint);
        canvas = null;
        Log.v("Homwight", "宽" + width + "高" + height);
        overlay = FastBlur.doBlur(overlay, (int) radius, true);
        return overlay;
    }

    private Animation showAnimation1(final View view, int fromY, int toY) {
        AnimationSet set = new AnimationSet(true);
        TranslateAnimation go = new TranslateAnimation(0, 0, fromY, toY);
        go.setDuration(300);
        TranslateAnimation go1 = new TranslateAnimation(0, 0, -10, 2);
        go1.setDuration(100);
        go1.setStartOffset(250);
        set.addAnimation(go1);
        set.addAnimation(go);

        set.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationStart(Animation animation) {

            }

        });
        return set;
    }


    public void showHomwriterWindow(View anchor, int bottomMargin) {
        final RelativeLayout layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.center_music_more_window, null);
        setContentView(layout);

        close = (ImageView) layout.findViewById(R.id.center_music_window_close);
        dian_earnx = layout.findViewById(R.id.earnx);
        dian_pepper = layout.findViewById(R.id.dian_pepper);
        dian_message = layout.findViewById(R.id.dian_message);
        dian_fl = layout.findViewById(R.id.dian_fl);
        dian_webtId = layout.findViewById(R.id.dian_webtId);
        /*android.widget.RelativeLayout.LayoutParams params =new android.widget.RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        params.bottomMargin = bottomMargin;
        params.addRule(RelativeLayout.BELOW, R.id.more_window_auto);
        params.addRule(RelativeLayout.RIGHT_OF, R.id.more_window_collect);
        params.topMargin = 200;
        params.leftMargin = 18;
        close.setLayoutParams(params);*/

        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isShowing()) {
                    closeAnimation(layout);
                    if (disslistener != null) {
                        disslistener.dis();
                    }
                }
            }

        });

        showAnimation(layout);
        setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), blur()));
        setOutsideTouchable(true);
        setFocusable(true);
        showAtLocation(anchor, Gravity.BOTTOM, 0, statusBarHeight);

    }

    public void setListener(Diss disslistener) {
        this.disslistener = disslistener;
    }

    /*
     * sp辣椒，su订阅，cc消息
     * type:0未请求时先隐藏，1请求后设置
     * */
    public void setImageDian() {
        dian_earnx.setVisibility((sp + su > 0) ? View.VISIBLE : View.GONE);


        dian_pepper.setVisibility(sp2 > 0 ? View.VISIBLE : View.GONE);

        dian_message.setVisibility(cc > 0 ? View.VISIBLE : View.GONE);

        dian_fl.setVisibility(fl > SettingManager.getInstance().getAuthorMessage("fl") ? View.VISIBLE : View.GONE);

        dian_webtId.setVisibility(webtId > 0 ? View.VISIBLE : View.GONE);


    }

    private void showAnimation(ViewGroup layout) {
        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.center_music_window_close) {
                continue;
            }
            child.setOnClickListener(this);
            child.setVisibility(View.INVISIBLE);
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    child.setVisibility(View.VISIBLE);
                    ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 600, 0);
                    fadeAnim.setDuration(600);
                    KickBackAnimator kickAnimator = new KickBackAnimator();
                    kickAnimator.setDuration(150);
                    fadeAnim.setEvaluator(kickAnimator);
                    fadeAnim.start();
                }
            }, i * 80);
        }

    }

    public void setSpuc(long sp, long su, long cc, long sp2, long webtId, long fl) {
        this.sp = sp;
        this.su = su;
        this.cc = cc;
        this.sp2 = sp2;
        this.webtId = webtId;
        this.fl = fl;
    }

    private void closeAnimation(ViewGroup layout) {

        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.center_music_window_close) {
                continue;
            }
            child.setOnClickListener(this);
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    child.setVisibility(View.VISIBLE);
                    ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 0, 1200);
                    fadeAnim.setDuration(600);
                    KickBackAnimator kickAnimator = new KickBackAnimator();
                    kickAnimator.setDuration(150);
                    fadeAnim.setEvaluator(kickAnimator);
                    fadeAnim.start();
                    fadeAnim.addListener(new Animator.AnimatorListener() {

                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            child.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                        }
                    });
                }
            }, (layout.getChildCount() - i - 1) * 50);

            if (child.getId() == R.id.more_window_local) {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        dismiss();
                        destroy();
                    }
                }, (layout.getChildCount() - i) * 30 + 400);
            }
        }


    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.more_window_local:
                intent = new Intent(mContext, CreatBookActivity.class);
                break;
            case R.id.more_window_online:
                intent = new Intent(mContext, MyincomeActivity.class);
                if (sp > 0) {
                    SettingManager.getInstance().putAuthorMessage("sp", sp);
                }
                if (su > 0) {
                    SettingManager.getInstance().putAuthorMessage("su", su);
                }

                dian_earnx.setVisibility(View.GONE);
                break;
            case R.id.more_window_delete:
                intent = new Intent(mContext, PepperharvestActivity.class);
                if (sp2 > 0) {
                    SettingManager.getInstance().putAuthorMessage("sp2", sp2);
                }

                dian_pepper.setVisibility(View.GONE);
                break;
            case R.id.more_window_collect:
                intent = new Intent(mContext, MyAuthorMessageActivity.class);
                dian_message.setVisibility(View.GONE);
                break;
            case R.id.more_window_auto:
                intent = new Intent(mContext, AuthorWealActivity.class);
                SettingManager.getInstance().putAuthorMessage("fl", fl);
                dian_fl.setVisibility(View.GONE);
                break;
            case R.id.more_window_external:
                intent = new Intent(mContext, AnnouncementActivity.class);
                SettingManager.getInstance().putAuthorMessage("webtId", webtId);
                dian_webtId.setVisibility(View.GONE);
                break;
            case R.id.more_window_readaid:
                intent = new Intent(mContext, ReaderAidActivity.class);

                break;
            case R.id.more_window_leave:
                intent = new Intent(mContext, LeaveActivity.class);
                break;

            default:
                return;
        }
        mContext.startActivity(intent);
    }

    public interface Diss {
        public void dis();
    }

    public void destroy() {

        if (null != overlay) {
            overlay.recycle();
            overlay = null;

        }
        if (null != mBitmap) {
            mBitmap.recycle();
            mBitmap = null;
        }
        System.gc();
        System.runFinalization();
        System.gc();
    }
}
